<template>
  <page-lr>
      <el-form size="small" :model="searchForm" label-width="90px" slot="content-right">
        <el-form-item label="水质指标：">
          <el-select v-model="searchForm.tag" placeholder="请选择" style="width:100%;" >
              <el-option v-for="(item,index) in initData.tag" :key="index" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统计类型：">
          <my-dateRange :start.sync="searchForm.start_date" :end.sync="searchForm.end_date" style="width:100%;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="getLionbayTile">启动反演</el-button>
          <el-button size="small">重置图层</el-button>
        </el-form-item>
      </el-form>
    <template slot="content-left">
      <div class="map" id="coordinates" ref="basicMapbox" style="height:100%;width:100%"></div>
    </template>
  </page-lr>
    
</template>

<script>
import * as mapboxgl from 'mapbox-gl';
import { stylesV8 } from '@/assets/js/config';
import lionbay from '@/assets/geojson/lionbay.js';
export default {

  data() {
    return {
      searchForm:{
        tag: 'tn',
        start_date: null,
        end_date: null,
      },
      map: null,
      mapboxToken: 'pk.eyJ1Ijoic25zcXNzIiwiYSI6ImNrZ2oxbWtqMTAzNnAyeXFwMDAzdmp2YTAifQ.AuaHmI9j-_VbOYxUSJACQw',
      _map: null,
      __mapResolvers: [],
      selStyle: stylesV8[1],
      initData:{
        tag:[
          {id: 'tn', name: '总氮(TN)'},
          {id: 'tp', name: '总磷(TP)'},
          {id: 'nh3_n', name: '氨氮(NH3-N)'},
          {id: 'd_o', name: '解氧(DO)'},
          {id: 'turbidity', name: '浊度(NTU)'},
          {id: 'ph', name: '酸碱度(pH)'},
          {id: 'codmn', name: '高锰酸盐指数(CODmn)'},
          {id: 'temp', name: '水温(TEMP)'},
        ]
      }
 
    }
  },
  created(){
    let d = this.$moment().subtract(1, 'years').format('YYYY-MM-DD');
    this.searchForm.start_date = this.$moment(d).add(1, 'd').format('YYYY-MM-DD');
    this.searchForm.end_date = this.$moment().format('YYYY-MM-DD');
    this.initMap();
    this.getLionbayTile();
    // this.getRegionSeries();
    // this.getPointSeries();
  },
  async mounted() {
    if (!mapboxgl.supported()) {
      this.$message.warning('您当前使用的浏览器不支持 Mapbox GL 地图');
    }
    const map = await this.createMap();
    this.setMap(map);
  },
  methods:{
    createMap(){
      return new Promise((resolve, reject) => {
        const map = new mapboxgl.Map({
          accessToken: this.mapboxToken,
          container: this.$refs.basicMapbox,
          style: 'mapbox://styles/mapbox/streets-v11',
          center: [113.5,23.1],
          zoom: 8,
          attributionControl: false,
          logoPosition: 'bottom-right',
          bearing: 0,
          preserveDrawingBuffer: true,
        });
        map.addControl(new mapboxgl.NavigationControl({
          showZoom: false,
          showCompass: false,
          visualizePitch: false
        }), 'bottom-left');
        map.on('load', () => {
          resolve(map);
          this.map = map;
          this.fitBounds();
          // this.mapChange.emit(map);
        });
      });
    },
    async initMap(callback) {
      const map = await this.getMap();
      this.map = map;
      this.interVal = setInterval(() => {
        map.resize();
      });
      // this.addStyleRaster();
      // this.addLayer()
      // this.addBorder();
      if(typeof(callback) == 'function'){
        callback();
      }
    },
    addStyleRaster(){
      const styles = this.selStyle.url.split('/');
      console.log(styles);
      this.map.addSource('basemap-style-source', {
        type: 'raster',
        scheme: 'xyz',
        tiles: [
          `https://api.mapbox.com/styles/v1/snsqss/${styles[styles.length - 1]}/tiles/512/{z}/{x}/{y}?access_token=${this.mapboxToken}`
        ]
      })
      this.map.addLayer({
        id: 'basemap-style-layer',
        type: 'raster',
        source: 'basemap-style-source',
        layout: {}
      }, 'split-layer');
    },
    addLayer(url){
      // 添加在线瓦片图层		
      this.map.addSource('tile_source', {
          type: 'raster',
          tiles: [url], // 替换为您的在线瓦片URL
          tileSize: 256
      });
      this.map.addLayer({
          id: 'tile_layer',
          type: 'raster',
          source: 'tile_source',
          paint: {}
      });
    },
    addBorder(){
      if (this.map.getLayer('area-border')) {
        this.map.removeLayer('area-border');
      }
      if (!this.map.getLayer('area-border')) {
        this.map.addLayer({
          id: 'area-border',
          type: 'line',
          'source': {
            'scheme':'tms',
            'type': 'vector',
            'tiles': [
                '/geoserver/gwc/service/tms/1.0.0/air:region@EPSG:900913@pbf/{z}/{x}/{y}.pbf'
            ]
          },
          'source-layer': 'region',
          filter: ['==', 'level', 1],
          minzoom: 1,
          maxzoom: 19,
          paint: {
            'line-color': '#2749B7',
            'line-width': 2
          }
        });
      }
    },
    getMap(){
      return new Promise((resolve, reject) => {
        if (!!this._map) {
          resolve(this._map);
          return;
        }
        if (!this._mapResolvers) {
          this._mapResolvers = [];
        }
        this._mapResolvers.push(resolve);
      });
    },
    setMap(map) {
      this._map = map;
      if (!!this._mapResolvers) {
        this._mapResolvers.forEach(resolve => resolve(map));
      }
    },
    async fitBounds(){
      if (!this.isPronvince && !this.isCity) {
        return;
      }
      const res = cityGeoJson;
      // const data = await res.json();
      const data = cityGeoJson;
      const geojson = data.features.find((i) => i.properties.name === city);
      const box = turf.bbox(this.isPronvince ? data : geojson);
      this.map.fitBounds([[box[0], box[1]], [box[2], box[3]]], {
        padding: 75,
        linear: false,
        animate: false
      });
    },
    getLionbayTile(){
      this.$request('post', '/lionbay/get_lionbay_tile', this.searchForm, (data,msg) => {
        console.log(data.local_url)
        let url = data.local_url.split('api-gee');
        this.addLayer('/api-gee' + url[1]);
      },msg => {

      }, {}, 'all')
    },
    getRegionSeries(){
      this.$request('post', '/lionbay/get_region_series', this.searchForm, (data,msg) => {

      })
    },
    getPointSeries(){
      this.$request('post', '/lionbay/get_point_series', this.searchForm, (data,msg) => {

      })
    },
  }
}
</script>